/**
 * financial.js - 理财产品页面脚本
 * 主文件处理页面初始化、筛选功能和标签页切换
 */

// 全局变量
let currentPage = 1;
let totalPages = 1;
let pageSize = 8;
let currentFilters = {};
let currentProductDetail = null;

document.addEventListener('DOMContentLoaded', function() {
  // 页面初始化
  const pageLayout = new PageLayout();
  pageLayout.init('financial');
  
  // 初始化功能
  initFilters();
  initTabs();
  initPagination();
  initModals();
  
  // 加载数据
  loadSummary();
  loadProducts();
  loadHotProducts();
  loadMyProducts();
});

/**
 * 初始化筛选区域
 */
function initFilters() {
  // 更新预期收益率滑块的值显示
  const minReturnSlider = document.getElementById('min-return');
  const minReturnValue = document.getElementById('min-return-value');
  
  minReturnSlider.addEventListener('input', () => {
    minReturnValue.textContent = minReturnSlider.value;
  });
  
  // 应用筛选按钮
  const applyFilterBtn = document.getElementById('apply-filter');
  applyFilterBtn.addEventListener('click', () => {
    applyFilters();
  });
  
  // 重置筛选按钮
  const resetFilterBtn = document.getElementById('reset-filter');
  resetFilterBtn.addEventListener('click', () => {
    resetFilters();
  });
}

/**
 * 应用筛选条件
 */
function applyFilters() {
  // 获取风险等级筛选
  const riskCheckboxes = document.querySelectorAll('input[name="risk"]:checked');
  const riskLevels = Array.from(riskCheckboxes).map(cb => parseInt(cb.value));
  
  // 获取投资期限筛选
  const durationCheckboxes = document.querySelectorAll('input[name="duration"]:checked');
  const durations = Array.from(durationCheckboxes).map(cb => cb.value);
  
  // 获取预期收益率筛选
  const minReturn = parseFloat(document.getElementById('min-return').value);
  
  // 设置筛选条件
  currentFilters = {
    riskLevels: riskLevels,
    durations: durations,
    minReturn: minReturn
  };
  
  // 重置页码并重新加载产品列表
  currentPage = 1;
  loadProducts();
  
  // 显示提示
  Toast.success('筛选条件已应用');
}

/**
 * 重置筛选条件
 */
function resetFilters() {
  // 重置风险等级复选框
  document.querySelectorAll('input[name="risk"]').forEach(cb => {
    cb.checked = false;
  });
  
  // 重置投资期限复选框
  document.querySelectorAll('input[name="duration"]').forEach(cb => {
    cb.checked = false;
  });
  
  // 重置预期收益率滑块
  const minReturnSlider = document.getElementById('min-return');
  const minReturnValue = document.getElementById('min-return-value');
  minReturnSlider.value = 1;
  minReturnValue.textContent = '1';
  
  // 清空筛选条件
  currentFilters = {};
  
  // 重置页码并重新加载产品列表
  currentPage = 1;
  loadProducts();
  
  // 显示提示
  Toast.success('筛选条件已重置');
}

/**
 * 初始化标签页切换
 */
function initTabs() {
  const tabs = document.querySelectorAll('.financial-tab');
  tabs.forEach(tab => {
    tab.addEventListener('click', () => {
      // 更新标签页状态
      tabs.forEach(t => t.classList.remove('active'));
      tab.classList.add('active');
      
      // 显示对应内容
      const tabId = tab.getAttribute('data-tab');
      document.querySelectorAll('.financial-content').forEach(content => {
        content.classList.remove('active');
      });
      
      let contentId;
      switch(tabId) {
        case 'all':
          contentId = 'all-products';
          break;
        case 'hot':
          contentId = 'hot-products';
          break;
        case 'my':
          contentId = 'my-products';
          loadMyProducts(); // 切换到我的理财时重新加载数据
          break;
        default:
          contentId = 'all-products';
      }
      
      document.getElementById(contentId).classList.add('active');
    });
  });
}

/**
 * 初始化分页控件
 */
function initPagination() {
  const prevBtn = document.querySelector('.pagination-btn[data-page="prev"]');
  const nextBtn = document.querySelector('.pagination-btn[data-page="next"]');
  
  prevBtn.addEventListener('click', () => {
    if (currentPage > 1) {
      currentPage--;
      loadProducts();
    }
  });
  
  nextBtn.addEventListener('click', () => {
    if (currentPage < totalPages) {
      currentPage++;
      loadProducts();
    }
  });
}

/**
 * 更新分页状态
 */
function updatePagination() {
  const currentPageElement = document.getElementById('current-page');
  const totalPagesElement = document.getElementById('total-pages');
  const prevBtn = document.querySelector('.pagination-btn[data-page="prev"]');
  const nextBtn = document.querySelector('.pagination-btn[data-page="next"]');
  
  currentPageElement.textContent = currentPage;
  totalPagesElement.textContent = totalPages;
  
  // 禁用或启用上一页/下一页按钮
  if (currentPage <= 1) {
    prevBtn.classList.add('disabled');
  } else {
    prevBtn.classList.remove('disabled');
  }
  
  if (currentPage >= totalPages) {
    nextBtn.classList.add('disabled');
  } else {
    nextBtn.classList.remove('disabled');
  }
}

/**
 * 初始化模态框
 */
function initModals() {
  // 产品详情模态框
  const productDetailModal = document.getElementById('product-detail-modal');
  const closeButtons = productDetailModal.querySelectorAll('.modal-close, .btn[data-dismiss="modal"]');
  
  closeButtons.forEach(button => {
    button.addEventListener('click', () => {
      productDetailModal.style.display = 'none';
    });
  });
  
  // 点击模态框外部关闭
  window.addEventListener('click', (event) => {
    if (event.target === productDetailModal) {
      productDetailModal.style.display = 'none';
    }
  });
  
  // 购买金额输入框监听
  const purchaseAmountInput = document.getElementById('purchase-amount');
  purchaseAmountInput.addEventListener('input', updateExpectedReturn);
  
  // 确认购买按钮
  const confirmPurchaseBtn = document.getElementById('confirm-purchase-btn');
  confirmPurchaseBtn.addEventListener('click', purchaseProduct);
  
  // 购买成功模态框
  const purchaseSuccessModal = document.getElementById('purchase-success-modal');
  const successCloseButtons = purchaseSuccessModal.querySelectorAll('.modal-close, .btn[data-dismiss="modal"]');
  
  successCloseButtons.forEach(button => {
    button.addEventListener('click', () => {
      purchaseSuccessModal.style.display = 'none';
    });
  });
  
  // 点击模态框外部关闭
  window.addEventListener('click', (event) => {
    if (event.target === purchaseSuccessModal) {
      purchaseSuccessModal.style.display = 'none';
    }
  });
  
  // 查看我的理财按钮
  const viewMyProductsBtn = document.getElementById('view-my-products-btn');
  viewMyProductsBtn.addEventListener('click', () => {
    purchaseSuccessModal.style.display = 'none';
    document.querySelector('.financial-tab[data-tab="my"]').click();
  });
}

/**
 * 加载摘要信息
 */
function loadSummary() {
  // 调用API获取投资摘要信息
  ApiService.get('/api/finance/summary')
    .then(response => {
      if (response.code === 0 && response.data) {
        const summary = response.data;
        
        // 更新摘要卡片
        document.getElementById('total-investment').textContent = Utils.formatMoney(summary.totalInvestment || 0);
        document.getElementById('expected-profit').textContent = Utils.formatMoney(summary.expectedProfit || 0);
        document.getElementById('holding-products').textContent = `${summary.holdingCount || 0} 个`;
      }
    })
    .catch(error => {
      console.error('获取投资摘要失败:', error);
      // 如果获取失败，显示默认值
      document.getElementById('total-investment').textContent = '¥0.00';
      document.getElementById('expected-profit').textContent = '¥0.00';
      document.getElementById('holding-products').textContent = '0 个';
    });
}

// 导入其他功能模块
document.write('<script src="/js/pages/financial-products.js"></script>');
document.write('<script src="/js/pages/financial-purchase.js"></script>');
